<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>体验websocket</title>
    <style>
      #contanier {
        width: 500px;
        height: 400px;
        border: 2px dashed #7575e7;
        overflow-y: auto;
      }
    </style>
  </head>

  <body>
    <div id="contanier"></div>
    <!-- 1  建立连接 (拨号) -->
    <!-- 2  发消息 接消息 -->
    <!-- 3  关闭连接 -->
    <input type="text" id="message" />
    <button id="btn1">建立连接</button>
    <button id="btn2">发送消息</button>
    <button id="btn3">关闭连接</button>

    <script>
      var dom = document.getElementById('contanier')
      var inputDom = document.getElementById('message')
      var btn1 = document.getElementById('btn1')
      var btn2 = document.getElementById('btn2')
      var btn3 = document.getElementById('btn3')
      var ws
      var falg = false
      btn1.addEventListener('click', function () {
        ws = new WebSocket('ws://121.40.165.18:8800 ')
        console.log(ws)
        //打开连接
        ws.onopen = function (event) {
          console.log('连接成功')
          falg = true
        }

        //连接失败
        ws.onerror = function () {
          console.log(建立链接失败)
        }
        //连接回复
        ws.onmessage = function (event) {
          dom.innerHTML += `<p style='color: aqua'>${event.data}</p>`
        }
        ws.onclose = function () {
          console.log('断开连接')
          dom.innerHTML += `<p>连接已断开</p>`
          falg = false
        }
      })

      btn2.onclick = function () {
        if (!falg) return
        const content = inputDom.value.trim()
        if (content.length === 0) {
          return console.log('内容不能为空')
        }
        ws.send(content)
        dom.innerHTML += `<p>${content}</p>`
        inputDom.value = ''
      }

      btn3.onclick = function () {
        ws.close() // 关闭连接
      }
    </script>
  </body>
</html>
